package org.jeecg.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.JsonObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.config.shiro.IgnoreAuth;
import org.jeecg.modules.system.entity.DataTime;
import org.jeecg.modules.system.entity.ZkPv;
import org.jeecg.modules.system.entity.ZkPvCount;
import org.jeecg.modules.system.service.IZkPvService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 缺陷表
 * @Author: jeecg-boot
 * @Date:   2024-05-27
 * @Version: V1.0
 */
@Api(tags="缺陷表")
@RestController
@RequestMapping("/ZkPv/zkPv")
@Slf4j
public class ZkPvController extends JeecgController<ZkPv, IZkPvService> {
	@Autowired
	private IZkPvService zkPvService;
	
	/**
	 * 分页列表查询
	 *
	 * @param zkPv
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "缺陷表-分页列表查询")
	@ApiOperation(value="缺陷表-分页列表查询", notes="缺陷表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ZkPv>> queryPageList(ZkPv zkPv,
											 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
											 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
											 HttpServletRequest req) {
		QueryWrapper<ZkPv> queryWrapper = QueryGenerator.initQueryWrapper(zkPv, req.getParameterMap());
		Page<ZkPv> page = new Page<ZkPv>(pageNo, pageSize);
		IPage<ZkPv> pageList = zkPvService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param zkPv
	 * @return
	 */
	@AutoLog(value = "缺陷表-添加")
	@ApiOperation(value="缺陷表-添加", notes="缺陷表-添加")
	@RequiresPermissions("ZkPv:zk_pv:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ZkPv zkPv) {
		zkPvService.save(zkPv);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param zkPv
	 * @return
	 */
	@AutoLog(value = "缺陷表-编辑")
	@ApiOperation(value="缺陷表-编辑", notes="缺陷表-编辑")
	@RequiresPermissions("ZkPv:zk_pv:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ZkPv zkPv) {
		zkPvService.updateById(zkPv);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "缺陷表-通过id删除")
	@ApiOperation(value="缺陷表-通过id删除", notes="缺陷表-通过id删除")
	@RequiresPermissions("ZkPv:zk_pv:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		zkPvService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "缺陷表-批量删除")
	@ApiOperation(value="缺陷表-批量删除", notes="缺陷表-批量删除")
	@RequiresPermissions("ZkPv:zk_pv:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.zkPvService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "缺陷表-通过id查询")
	@ApiOperation(value="缺陷表-通过id查询", notes="缺陷表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ZkPv> queryById(@RequestParam(name="id",required=true) String id) {
		ZkPv zkPv = zkPvService.getById(id);
		if(zkPv==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(zkPv);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param zkPv
    */
    @RequiresPermissions("ZkPv:zk_pv:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZkPv zkPv) {
        return super.exportXls(request, zkPv, ZkPv.class, "缺陷表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("ZkPv:zk_pv:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ZkPv.class);
    }

	/**
	 * ①当班产品不合格数据统计（表头需要前端自己计算获取小时，并往前推一个小时例：8-1为8点钟的数据）
	 */
	@IgnoreAuth
	@AutoLog(value = "BS当班产品不合格数据统计")
	@ApiOperation(value="BS当班产品不合格数据统计", notes="BS当班产品不合格数据统计")
	@GetMapping(value = "/queryEq0")
	public Result<?> queryEq0(String productFloor) {
		List<List<ZkPv>> list=new ArrayList();
		// 获取当前日期和时间
		LocalDateTime now = LocalDateTime.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH");

		int h=1;
		//循环当前及前八个小时的数据
		for(int i=8;i>0;i--){
			//获取前一个小时完整时间
			LocalDateTime oneHourAgo = now.minus(Duration.ofHours(h++));
			String dateTime=formatter.format(oneHourAgo);
			//获取再前一小时的完整时间
			LocalDateTime oneHourAgo1 = oneHourAgo.minus(Duration.ofHours(1));
			String dateTimeAgo=formatter.format(oneHourAgo1);
			//获取前一天时间的数据
			List<ZkPv> zkPv=this.zkPvService.queryEq(dateTime,productFloor);
			//获取再前一天时间的数据
			List<ZkPv> zkPv1=this.zkPvService.queryEq(dateTimeAgo,productFloor);

			List<ZkPv> list1= new ArrayList<>();
			for(int k=0;k<6;k++){
				ZkPv ZkPv1= zkPv.get(k);
				ZkPv ZkPv2= zkPv1.get(k);
				ZkPv zkPv0=new ZkPv();
				zkPv0.setTime(ZkPv1.getTime());
				zkPv0.setTagName(ZkPv1.getTagName());
				zkPv0.setPvValue(String.valueOf(Integer.parseInt(ZkPv1.getPvValue())-Integer.parseInt(ZkPv2.getPvValue())));
				list1.add(zkPv0);
			}
			list.add(list1);
		}


		return Result.OK(list);
	}

    /**
     * ②查询24小时所有缺陷数量的总和
     */
	@IgnoreAuth
	@AutoLog(value = "BS查询24小时所有缺陷数量的总和")
    @ApiOperation(value="BS查询24小时所有缺陷数量的总和", notes="BS查询24小时所有缺陷数量的总和")
    @GetMapping(value = "/queryCount")
    public Result<?> queryCount(String productFloor) {
        List<ZkPvCount> list=new ArrayList<>();
        // 获取当前日期和时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH");
        //获取当前时间的小时进行循环判断
        DateTimeFormatter formatterh = DateTimeFormatter.ofPattern("HH");
        String newHH=formatterh.format(now);
        //首先装载当前时间的数据
		ZkPvCount zkPvCount0=new ZkPvCount();
		String count0=this.zkPvService.queryCount(formatter.format(now),productFloor);
		int h=1;
		String zkPvCount1;
		String zkPvCount2;

		if(count0==null||count0==""){
			zkPvCount0.setTime(formatterh.format(now));
			zkPvCount0.setCount(null);
			list.add(zkPvCount0);
			for(int i=Integer.parseInt(newHH)-1;i>=0;i--){
				//获取前一个小时完整时间
				LocalDateTime oneHourAgo = now.minus(Duration.ofHours(h++));
				String dateTime=formatter.format(oneHourAgo);
				//获取再前一小时的完整时间
				LocalDateTime oneHourAgo1 = oneHourAgo.minus(Duration.ofHours(1));
				String dateTimeAgo=formatter.format(oneHourAgo1);
				//获取前一个小时数据
				 zkPvCount1 = this.zkPvService.queryCount(dateTime, productFloor);
				//获取再前一个小时数据
				 zkPvCount2 = this.zkPvService.queryCount(dateTimeAgo, productFloor);
				if(zkPvCount1==null ||zkPvCount2==null){
					zkPvCount1="0";
					zkPvCount2="0";
				}
					//两次时间获取到的数据作差放入新对象中
					Integer count = Integer.parseInt(zkPvCount1) - Integer.parseInt(zkPvCount2);
					//创建新对象往LIST中扔数据
					ZkPvCount zkPvCount3=new ZkPvCount();
					zkPvCount3.setCount(String.valueOf(count));
					zkPvCount3.setTime(formatterh.format(oneHourAgo));
					list.add(zkPvCount3);
			}
		}else {
			for(int i=Integer.parseInt(newHH)-1;i>=0;i--) {
				//获取当前日期的前一个小时完整时间
				LocalDateTime oneHourAgo = now.minus(Duration.ofHours(h++));
				String dateTime = formatter.format(oneHourAgo);
				//获取前当前小时数据
				 zkPvCount1 = this.zkPvService.queryCount(formatter.format(now), productFloor);
				//获取前一个小时数据
				 zkPvCount2 = this.zkPvService.queryCount(dateTime, productFloor);
				if(zkPvCount1==null ||zkPvCount2==null){
					zkPvCount1="0";
					zkPvCount2="0";
				}
					//两次时间获取到的数据作差放入新对象中
					Integer count = Integer.parseInt(zkPvCount1) - Integer.parseInt(zkPvCount2);
					//创建新对象往LIST中扔数据
					ZkPvCount zkPvCount3 = new ZkPvCount();
					zkPvCount3.setCount(String.valueOf(count));
					zkPvCount3.setTime(formatter.format(now));
					list.add(zkPvCount3);

			}
		}

        return Result.OK(list);
    }

	/**
	 * ③查询近30天每天各缺陷类数量的叠层
	 */
	@IgnoreAuth
	@AutoLog(value = "BS查询近30天每天各缺陷类数量的叠层")
	@ApiOperation(value="BS查询近30天每天各缺陷类数量的叠层", notes="BS查询近30天每天各缺陷类数量的叠层")
	@GetMapping(value = "/queryAll")
	public Result<?> queryAll(String productFloor) {
		List<List<ZkPv>> list=new ArrayList();
		//获取当前时间
		LocalDateTime now = LocalDateTime.now();
		//时间格式（年，月，日）
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd 23");
		//首先装载当前时间的数据
		List<ZkPv> list0=new ArrayList<>();
		list0=this.zkPvService.queryAll(formatter.format(now),productFloor);
		int dd=1;

		if(list0.size()==0){
			for(int i=30;i>=0;i--){
				//获取当前时间的前一天
				LocalDateTime previousDay = now.minusDays(dd++);
				String newTime=formatter.format(previousDay);
				//获取前一天的再前一天时间
				LocalDateTime previousDayAgo = previousDay.minusDays(1);
				String newTimeAgo=formatter.format(previousDayAgo);
				//获取前一天时间的数据
				List<ZkPv> zkPv=this.zkPvService.queryAll(newTime,productFloor);
				//获取再前一天时间的数据
				List<ZkPv> zkPv1=this.zkPvService.queryAll(newTimeAgo,productFloor);

				if(zkPv.size()==0 ||zkPv1.size()==0){
					list.add(list0);
				}else{
					List<ZkPv> list1= new ArrayList<>();
					for(int h=0;h<6;h++){
						ZkPv ZkPv1= zkPv.get(h);
						ZkPv ZkPv2= zkPv1.get(h);
						ZkPv zkPv0=new ZkPv();
						zkPv0.setTime(ZkPv1.getTime());
						zkPv0.setTagName(ZkPv1.getTagName());
						zkPv0.setPvValue(String.valueOf(Integer.parseInt(ZkPv1.getPvValue())-Integer.parseInt(ZkPv2.getPvValue())));
						list1.add(zkPv0);
					}
					list.add(list1);
				}
			}
		}else {
			for (int i = 29; i >= 0; i--) {
				//获取当前时间的前一天时间
				LocalDateTime previousDayAgo = now.minusDays(dd++);
				String newTimeAgo = formatter.format(previousDayAgo);
				//获取当前时间的数据
				List<ZkPv> zkPv = this.zkPvService.queryAll(formatter.format(now), productFloor);
				//获取当前时间的前一天时间数据
				List<ZkPv> zkPv1 = this.zkPvService.queryAll(newTimeAgo, productFloor);
				if (zkPv.size() == 0 || zkPv1.size() == 0) {
					list.add(list0);
				} else {
					List<ZkPv> list1 = new ArrayList<>();
					for (int h = 0; h < 6; h++) {
						ZkPv ZkPv1 = zkPv.get(h);
						ZkPv ZkPv2 = zkPv1.get(h);
						ZkPv zkPv0 = new ZkPv();
						zkPv0.setTime(ZkPv1.getTime());
						zkPv0.setTagName(ZkPv1.getTagName());
						zkPv0.setPvValue(String.valueOf(Integer.parseInt(ZkPv1.getPvValue()) - Integer.parseInt(ZkPv2.getPvValue())));
						list1.add(zkPv0);
					}
					list.add(list1);
				}
			}
		}
		return Result.OK(list);
	}


	/**
	 * ④PC查询报表
	 */
	@AutoLog(value = "PC端查询报表")
	@ApiOperation(value="PC端查询报表", notes="PC端查询报表")
	@PostMapping(value = "/queryEqReport")
	public Result<?> queryEqReport (@RequestBody DataTime dataTime) {
		List<List<ZkPv>> list=new ArrayList();
		String productFloor=dataTime.getProductFloor();
		String starTime=dataTime.getStarTime().substring(0,19);
		String endTime=dataTime.getEndTime().substring(0,19);
		//整理开始时间和结束时间
		DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		DateTimeFormatter formatter0 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH");

		LocalDateTime starTime0 = LocalDateTime.parse(starTime, formatter1);
		LocalDateTime endTime0 = LocalDateTime.parse(endTime, formatter1);
		//两个时间作差获取小时数
		Duration duration = Duration.between(starTime0,endTime0);
		long hoursBetween = duration.toHours();

		if(hoursBetween<24){
			int a=0;
			for(int i=0;i<=hoursBetween;i++){
				//获取前一个小时完整时间
				LocalDateTime oneHourAgo = endTime0.minus(Duration.ofHours(a++));
				String dateTime=formatter0.format(oneHourAgo);
				//获取再前一小时的完整时间
				LocalDateTime oneHourAgo1 = oneHourAgo.minus(Duration.ofHours(1));
				String dateTimeAgo=formatter0.format(oneHourAgo1);
				//获取前一天时间的数据
				List<ZkPv> zkPv=this.zkPvService.queryEq(dateTime,productFloor);
				//获取再前一天时间的数据
				List<ZkPv> zkPv1=this.zkPvService.queryEq(dateTimeAgo,productFloor);

				if(zkPv.size()==0||zkPv1.size()==0){
					List<ZkPv> list3= new ArrayList<>();
					ZkPv zkPv2=new ZkPv();
					list3.add(zkPv2.setTime(formatter1.format(oneHourAgo1)));
					list.add(list3);
				}
				List<ZkPv> list1= new ArrayList<>();
				for(int k=0;k<6;k++){
					ZkPv ZkPv1= zkPv.get(k);
					ZkPv ZkPv2= zkPv1.get(k);
					ZkPv zkPv0=new ZkPv();
					zkPv0.setTime(ZkPv2.getTime());
					zkPv0.setTagName(ZkPv1.getTagName());
					zkPv0.setPvValue(String.valueOf(Integer.parseInt(ZkPv1.getPvValue())-Integer.parseInt(ZkPv2.getPvValue())));
					list1.add(zkPv0);
				}
				list.add(list1);
			}
		}else {
			//计算天数进行循环
			int days = (int) Math.floor((double) hoursBetween / 24);
			int a=0;
			for(int i=0;i<=days;i++){
				//获取前一天时间
				LocalDateTime oneHourAgo = endTime0.minusDays(a++);
				String dateTime=formatter0.format(oneHourAgo);
				//获取再前一天时间
				LocalDateTime oneHourAgo1 = oneHourAgo.minusDays(1);
				String dateTimeAgo=formatter0.format(oneHourAgo1);
				//获取前一天时间的数据
				List<ZkPv> zkPv=this.zkPvService.queryEq(dateTime,productFloor);
				//获取再前一天时间的数据
				List<ZkPv> zkPv1=this.zkPvService.queryEq(dateTimeAgo,productFloor);
				if(zkPv.size()==0||zkPv1.size()==0){
					List<ZkPv> list3= new ArrayList<>();
					ZkPv zkPv2=new ZkPv();
					list3.add(zkPv2.setTime(formatter1.format(oneHourAgo1)));
					list.add(list3);
				}else{
					List<ZkPv> list1= new ArrayList<>();
					for(int k=0;k<6;k++){
						ZkPv ZkPv1= zkPv.get(k);
						ZkPv ZkPv2= zkPv1.get(k);
						ZkPv zkPv0=new ZkPv();
						zkPv0.setTime(ZkPv2.getTime());
						zkPv0.setTagName(ZkPv1.getTagName());
						zkPv0.setPvValue(String.valueOf(Integer.parseInt(ZkPv1.getPvValue())-Integer.parseInt(ZkPv2.getPvValue())));
						list1.add(zkPv0);
					}
					list.add(list1);
				}
			}
		}
		return Result.OK(list);
	}

	/**
	 * ⑤1573系统集成
	 */
	@AutoLog(value = "1573系统集成")
	@ApiOperation(value="1573系统集成", notes="1573系统集成")
	@PostMapping(value = "/query1573")
	public Result<?> query1573 (@RequestBody JsonObject jsonObject) {


		return Result.OK();
	}
}
